<template>
  <el-col :span="span">
    <el-form-item
      class="ne-line"
      :label="component.attrName || cityName"
      :prop="getProp"
      v-show="this.formData[formId].isshow"
      required
    >
      <el-input
        v-show="false"
        v-model="
          formData[component.pageTempStructId + '-' + component.attrId].value
        "
      />
      <el-select
        :disabled="isSelect"
        v-if="address.hasOwnProperty('country')"
        filterable
        v-model="address.country"
        placeholder="国家"
        class="ne-select-s"
        style="width: 100%"
        @change="selectCounty"
      >
        <el-option
          v-for="item in countries"
          :key="item.locId"
          :label="item.locName"
          :value="item.locId"
        >
        </el-option>
      </el-select>
      <el-select
        v-if="address.hasOwnProperty('provice')"
        filterable
        v-model="address.provice"
        placeholder="省"
        class="ne-select-s"
        style="width: 100%"
        @change="selectProvice"
      >
        <el-option
          v-for="item in provices"
          :key="item.locId"
          :label="item.locName"
          :value="item.locId"
        >
        </el-option>
      </el-select>
      <el-select
        v-if="address.hasOwnProperty('city')"
        filterable
        v-model="address.city"
        placeholder="市"
        class="ne-select-s"
        style="width: 100%"
        @change="selectCity"
      >
        <el-option
          v-for="item in citys"
          :key="item.locId"
          :label="item.locName"
          :value="item.locId"
        >
        </el-option>
      </el-select>
      <el-select
        v-if="address.hasOwnProperty('area')"
        filterable
        v-model="address.area"
        placeholder="县"
        class="ne-select-s"
        style="width: 100%"
        @change="selectArea"
      >
        <el-option
          v-for="item in areas"
          :key="item.locId"
          :label="item.locName"
          :value="item.locId"
        >
        </el-option>
      </el-select>
    </el-form-item>
  </el-col>
</template>

<script>
import mixinstype20 from "../mixins/mixinstype20";
import http from "../../utils/http";
// import ValidateMap from "../../utils/validate-map";
// import Selector from "./selector.vue";
import { mapState } from 'vuex'
export default {
  name: "CitySelector",
  mixins: [mixinstype20],
  data() {
    return {
      countries: [],
      provices: [],
      citys: [],
      areas: [],
      formId: "",
      address: {},
      addressMap: {
        country: { country: "", provice: "", city: "", area: "" },
        provice: { provice: "", city: "", area: "" },
        city: { city: "", area: "" },
        area: { area: "" },
      },
      param: {
        qryType: "", //查询下级的级别  COUNTRY国家 PROVIENCE 省  CITY 市  县
        preLocId: "", //当前选择的 ,上一个组织的locId
        preRegionId: "", //暂时默认不填。当前选择的,preLocId和preRegionId选一个传或都传,上一个组织的RegionId，
      },
    };
  },
  props: {
    cityName: {
      type: String,
      default: () => {
        return "城市";
      },
    },
    isSelect: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    value: [String, Number],

    component: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },

  watch: {
    /**
     * activeTemplateId
     */
    activeTemplateId(){
      this.citys = []
    },
    /**
     * 监听收藏反显的导致address的变化
     */
    "address.city": {
      async handler(val) {
        // 存储变化前的值
        const { provice, area } = this.address;
        if (val && !this.citys.length) {
          await this.selectProvice(provice);
          this.address.city = val;
          if (area) {
            await this.selectCity(val);
            this.address.area = area;
          }
        }
      },
    },
  },
  created() {
    // 定义校验规则
    // this.ruleData.rules[
    //   this.component.pageTempStructId + "-" + this.component.attrId + ".value"
    // ] = [{ required: true, message: `城市不能为空`, trigger: "change" }];
    this.formId = this.component.pageTempStructId + "-" + this.component.attrId; //组件绑定ID
    this.formData[this.formId].value = this.currval;
    this.formData[this.formId].options = [];
    let address = { country: "26068", provice: "", city: "", area: "" };
    this.formData[this.formId].options.push(address);
    this.address = this.formData[this.formId].options[0];
    this.initContry();
    this.selectCounty();
  },
  computed: {
    // 该属性备用:在把当前组件作为属性配置时使用
    currval: {
      get: function () {
        return this.value;
      },
      set: function (newValue) {
        this.$emit("input", newValue);
      },
    },
    getAddress() {
      let key = this.actionValue.split("|")[1] || "country";
      return this.addressMap[key];
    },
    getProp() {
      let prop =
        this.component.pageTempStructId +
        "-" +
        this.component.attrId +
        ".value";
      return prop;
    },
    /**
     * 引入选择收藏模板标记
     */
    ...mapState('collect',['activeTemplateId'])
  },
  // components: { Selector },
  methods: {
    selected(address) {
      //
      let ppm = this.ruleData["ppm"];
      let obj = {
        address: address,
        key: this.component.pageTempStructId + "-" + this.component.attrId,
      };
      this.$emit("getPluginValue", obj);
      if (address.area || address.city || address.country || address.provice) {
        ppm.$refs.ppmRef.clearValidate(
          this.component.pageTempStructId +
            "-" +
            this.component.attrId +
            ".value"
        );
      } else {
        ppm.$refs.ppmRef.validateField(
          this.component.pageTempStructId +
            "-" +
            this.component.attrId +
            ".value"
        );
      }
    },
    initContry() {
      this.param.qryType = "COUNTRY";
      this.param.preLocId = this.address.country;
      this.getCity(this.param).then((result) => {
        if (result.code == 200) {
          this.countries = result.meta.cityList;
          this.countries.forEach((item) => {
            if (item.locId == this.param.preLocId) {
              this.address.country = item.locId;
            }
          });
        }
      });
      let obj = {
        address: this.address,
        key: this.component.pageTempStructId + "-" + this.component.attrId,
      };
      this.$emit("getPluginValue", obj);
    },
    async selectCounty(val) {
      //选择国家
      if (val) {
        //选择情况下触发事件清空值，初始化赋值不清空
        this.address.provice = "";
        this.address.city = "";
        this.address.area = "";
      }
      // this.provices = [];
      // this.citys = [];
      // this.areas = [];
      //渲染省列表
      this.param.qryType = "PROVIENCE";
      this.param.preLocId = this.address.country;
      await this.getCity(this.param).then((result) => {
        if (result.code == 200) {
          this.provices = result.meta.cityList;
        }
      });
      this.onSelected(this.address);
      let obj = {
        address: this.address,
        key: this.component.pageTempStructId + "-" + this.component.attrId,
      };

      this.$emit("getPluginValue", obj);
    },

    async selectProvice(val) {
      //选择省
      if (val) {
        //选择情况下触发事件清空值，初始化赋值不清空
        this.address.city = "";
        this.address.area = "";
      }
      // this.citys = [];
      // this.areas = [];
      //渲染市列表
      this.param.qryType = "CITY";
      this.param.preLocId = val;
      this.onSelected(this.address);
      let obj = {
        address: this.address,
        key: this.component.pageTempStructId + "-" + this.component.attrId,
      };
      this.$emit("getPluginValue", obj);
      if (val == 27528) return;
      await this.getCity(this.param).then((result) => {
        if (result.code == 200) {
          this.citys = result.meta.cityList;
        }
      });
    },

    async selectCity(val) {
      //选择城市
      if (val) {
        //选择情况下触发事件清空值，初始化赋值不清空
        this.address.area = "";
      }
      // this.areas = [];
      //渲染区域列表
      this.param.qryType = "CITY";
      this.param.preLocId = val;
      await this.getCity(this.param).then((result) => {
        if (result.code == 200) {
          this.areas = result.meta.cityList;
        }
      });
      this.onSelected(this.address);
      let obj = {
        address: this.address,
        key: this.component.pageTempStructId + "-" + this.component.attrId,
      };
      this.$emit("getPluginValue", obj);
    },

    selectArea() {
      //选择区域

      this.onSelected(this.address);
      let obj = {
        address: this.address,
        key: this.component.pageTempStructId + "-" + this.component.attrId,
      };
      this.$emit("getPluginValue", obj);
    },

    onSelected(address) {
      //
      let result,
        { country, provice, city, area } = address;
      if (area) result = area;
      else if (city) result = city;
      else if (provice) result = provice;
      else if (country) result = country;
      else result = "";
      this.formData[
        this.component.pageTempStructId + "-" + this.component.attrId
      ].value = result;
    },
    async getCity(params) {
      let res = await http({
        url: `${process.env.VUE_APP_CTX_ORDER_QUERY}/qryCityList`,
        data: params,
        method: "GET",
      });
      return res;
    },
  },
};
</script>
